<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>企业日历系统</title>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/element-plus/dist/index.full.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        .calendar-container {
            padding: 20px;
            background-color: #f5f5f5;
            min-height: 100vh;
        }
        .calendar-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .calendar-main {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .workday {
            background-color: #e8f5e8 !important;
        }
        .holiday {
            background-color: #ffe8e8 !important;
        }
        .custom-date {
            background-color: #e8f0ff !important;
        }
        .date-info {
            font-size: 12px;
            color: #666;
        }
        .upload-area {
            border: 2px dashed #d9d9d9;
            border-radius: 6px;
            width: 100%;
            height: 180px;
            text-align: center;
            cursor: pointer;
            position: relative;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
        }
        .upload-area:hover {
            border-color: #409eff;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="calendar-container">
            <!-- 头部 -->
            <div class="calendar-header">
                <div>
                    <h1>企业日历系统</h1>
                    <p>支持多公司自定义工作日与节假日管理</p>
                </div>
                <div>
                    <el-select v-model="selectedCompany" placeholder="选择公司" style="width: 200px; margin-right: 10px;">
                        <el-option
                            v-for="company in companies"
                            :key="company.id"
                            :label="company.companyName"
                            :value="company.id">
                        </el-option>
                    </el-select>
                    <el-button type="primary" @click="refreshCalendar">刷新</el-button>
                </div>
            </div>

            <!-- 主内容区域 -->
            <div class="calendar-main">
                <!-- 工具栏 -->
                <div style="padding: 20px; border-bottom: 1px solid #ebeef5;">
                    <!-- 月份导航 -->
                    <div style="margin-bottom: 20px; text-align: center;">
                        <el-button @click="previousMonth">
                            <el-icon><ArrowLeft /></el-icon>
                            上个月
                        </el-button>
                        <el-button @click="goToToday" style="margin: 0 10px;">
                            <el-icon><Calendar /></el-icon>
                            今天
                        </el-button>
                        <el-button @click="nextMonth">
                            下个月
                            <el-icon><ArrowRight /></el-icon>
                        </el-button>
                        <span style="margin-left: 20px; font-size: 18px; font-weight: bold;">
                            {{ currentYear }}年{{ currentMonth }}月
                        </span>
                    </div>
                    
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-button type="success" @click="showAddHolidayDialog = true" :disabled="!selectedCompany">
                                <el-icon><Plus /></el-icon>
                                添加节假日
                            </el-button>
                        </el-col>
                        <el-col :span="6">
                            <el-button type="warning" @click="showImportDialog = true" :disabled="!selectedCompany">
                                <el-icon><Upload /></el-icon>
                                导入Excel
                            </el-button>
                        </el-col>
                        <el-col :span="6">
                            <el-button type="info" @click="exportHolidays" :disabled="!selectedCompany">
                                <el-icon><Download /></el-icon>
                                导出Excel
                            </el-button>
                        </el-col>
                        <el-col :span="6">
                            <el-button type="primary" @click="downloadTemplate">
                                <el-icon><Document /></el-icon>
                                下载模板
                            </el-button>
                        </el-col>
                    </el-row>
                </div>

                <!-- 日历组件 -->
                <div style="padding: 20px;">
                    <el-calendar v-model="currentDate" @change="onDateChange">
                        <template #date-cell="{ date, data }">
                            <div class="calendar-cell" :class="getCellClass(data)">
                                <div class="date-info">
                                    <div style="font-weight: bold; font-size: 14px;">{{ data.day }}</div>
                                    <div v-if="getDateInfo(date)" class="date-info" style="font-size: 11px; margin-top: 2px;">
                                        <div v-if="getDateInfo(date).isWorkday !== undefined">
                                            {{ getDateInfo(date).isWorkday ? '工作日' : '休息日' }}
                                        </div>
                                        <div v-if="getDateInfo(date).typeName" style="color: #409eff; font-weight: bold;">
                                            {{ getDateInfo(date).typeName }}
                                        </div>
                                        <div v-if="getDateInfo(date).description" style="color: #666;">
                                            {{ getDateInfo(date).description }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </el-calendar>
                </div>
            </div>
        </div>

        <!-- 添加节假日对话框 -->
        <el-dialog v-model="showAddHolidayDialog" title="添加节假日" width="500px">
            <el-form :model="holidayForm" :rules="holidayRules" ref="holidayFormRef" label-width="100px">
                <el-form-item label="节假日名称" prop="holidayName">
                    <el-input v-model="holidayForm.holidayName" placeholder="请输入节假日名称"></el-input>
                </el-form-item>
                <el-form-item label="日期" prop="holidayDate">
                    <el-date-picker
                        v-model="holidayForm.holidayDate"
                        type="date"
                        placeholder="选择日期"
                        style="width: 100%">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="类型" prop="typeId">
                    <el-select v-model="holidayForm.typeId" placeholder="选择类型" style="width: 100%">
                        <el-option
                            v-for="type in holidayTypes"
                            :key="type.id"
                            :label="type.typeName"
                            :value="type.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否工作日">
                    <el-switch v-model="holidayForm.isWorkday"></el-switch>
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="holidayForm.description" type="textarea" placeholder="请输入描述"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="showAddHolidayDialog = false">取消</el-button>
                <el-button type="primary" @click="addHoliday">确定</el-button>
            </template>
        </el-dialog>

        <!-- 导入Excel对话框 -->
        <el-dialog v-model="showImportDialog" title="导入节假日" width="500px">
            <div class="upload-area" @click="triggerFileInput">
                <input ref="fileInput" type="file" accept=".xlsx,.xls" @change="handleFileSelect" style="display: none;">
                <el-icon size="40" color="#c0c4cc"><Upload /></el-icon>
                <div style="margin-top: 10px; color: #606266;">
                    点击上传Excel文件
                </div>
                <div style="margin-top: 5px; color: #909399; font-size: 12px;">
                    支持 .xlsx, .xls 格式，文件大小不超过10MB
                </div>
            </div>
            <div v-if="selectedFile" style="margin-top: 20px;">
                <el-alert
                    :title="`已选择文件: ${selectedFile.name}`"
                    type="info"
                    show-icon>
                </el-alert>
            </div>
            <template #footer>
                <el-button @click="showImportDialog = false">取消</el-button>
                <el-button type="primary" @click="importHolidays" :disabled="!selectedFile">导入</el-button>
            </template>
        </el-dialog>
    </div>

    <script>
        const { createApp } = Vue;
        const { ElMessage, ElMessageBox } = ElementPlus;

        createApp({
            data() {
                return {
                    // 基础数据
                    companies: [],
                    selectedCompany: null,
                    currentDate: new Date(),
                    calendarData: [],
                    dateInfoMap: new Map(), // 存储日期详细信息
                    
                    // 对话框控制
                    showAddHolidayDialog: false,
                    showImportDialog: false,
                    
                    // 节假日表单
                    holidayForm: {
                        companyId: null,
                        holidayName: '',
                        holidayDate: null,
                        typeId: null,
                        isWorkday: false,
                        description: ''
                    },
                    holidayRules: {
                        holidayName: [
                            { required: true, message: '请输入节假日名称', trigger: 'blur' }
                        ],
                        holidayDate: [
                            { required: true, message: '请选择日期', trigger: 'change' }
                        ],
                        typeId: [
                            { required: true, message: '请选择类型', trigger: 'change' }
                        ]
                    },
                    
                    // 节假日类型
                    holidayTypes: [],
                    
                    // 文件上传
                    selectedFile: null
                }
            },
            computed: {
                currentYear() {
                    return this.currentDate.getFullYear();
                },
                currentMonth() {
                    return this.currentDate.getMonth() + 1;
                }
            },
            mounted() {
                this.loadCompanies();
                this.loadHolidayTypes();
            },
            methods: {
                // 加载公司列表
                async loadCompanies() {
                    try {
                        const response = await axios.get('/api/companies');
                        this.companies = response.data;
                        if (this.companies.length > 0) {
                            this.selectedCompany = this.companies[0].id;
                            this.holidayForm.companyId = this.selectedCompany;
                            this.refreshCalendar();
                        }
                    } catch (error) {
                        ElMessage.error('加载公司列表失败: ' + error.message);
                    }
                },
                
                // 加载节假日类型
                async loadHolidayTypes() {
                    try {
                        // 这里应该调用API获取节假日类型，暂时使用默认数据
                        this.holidayTypes = [
                            { id: 1, typeName: '法定节假日', typeCode: 'LEGAL_HOLIDAY' },
                            { id: 2, typeName: '公司节假日', typeCode: 'COMPANY_HOLIDAY' },
                            { id: 3, typeName: '调休工作日', typeCode: 'WORK_DAY' },
                            { id: 4, typeName: '特殊工作日', typeCode: 'SPECIAL_WORK' }
                        ];
                    } catch (error) {
                        ElMessage.error('加载节假日类型失败: ' + error.message);
                    }
                },
                
                // 刷新日历
                async refreshCalendar() {
                    if (!this.selectedCompany) return;
                    
                    try {
                        const year = this.currentDate.getFullYear();
                        const month = this.currentDate.getMonth() + 1;
                        
                        const response = await axios.get(`/api/calendar/month/${this.selectedCompany}`, {
                            params: { year, month }
                        });
                        
                        this.calendarData = response.data;
                        this.updateDateInfoMap();
                    } catch (error) {
                        ElMessage.error('加载日历数据失败: ' + error.message);
                    }
                },
                
                // 更新日期信息映射
                updateDateInfoMap() {
                    this.dateInfoMap.clear();
                    this.calendarData.forEach(day => {
                        const dateKey = this.formatDateKey(day.date);
                        this.dateInfoMap.set(dateKey, day);
                    });
                },
                
                // 格式化日期键
                formatDateKey(date) {
                    if (typeof date === 'string') {
                        return date;
                    }
                    const d = new Date(date);
                    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
                },
                
                // 获取日期信息
                getDateInfo(date) {
                    const dateKey = this.formatDateKey(date);
                    return this.dateInfoMap.get(dateKey);
                },
                
                // 上个月
                previousMonth() {
                    const newDate = new Date(this.currentDate);
                    newDate.setMonth(newDate.getMonth() - 1);
                    this.currentDate = newDate;
                    this.refreshCalendar();
                },
                
                // 下个月
                nextMonth() {
                    const newDate = new Date(this.currentDate);
                    newDate.setMonth(newDate.getMonth() + 1);
                    this.currentDate = newDate;
                    this.refreshCalendar();
                },
                
                // 回到今天
                goToToday() {
                    this.currentDate = new Date();
                    this.refreshCalendar();
                },
                
                // 更新日历显示
                updateCalendarDisplay() {
                    // 这里需要根据实际的数据结构来更新日历显示
                    // Element Plus的日历组件可能需要特殊处理
                },
                
                // 获取单元格样式
                getCellClass(data) {
                    const dateInfo = this.getDateInfo(data.date);
                    if (dateInfo) {
                        if (dateInfo.isWorkday === true) {
                            return 'workday';
                        } else if (dateInfo.isWorkday === false) {
                            return 'holiday';
                        }
                        if (dateInfo.isCustomDate) {
                            return 'custom-date';
                        }
                    }
                    return '';
                },
                
                // 日期变化事件
                onDateChange(date) {
                    this.currentDate = date;
                    this.refreshCalendar();
                },
                
                // 格式化日期为 YYYY-MM-DD 格式，避免时区问题
                formatDateForAPI(date) {
                    if (!date) return null;
                    
                    // 如果是字符串格式的日期，直接返回
                    if (typeof date === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(date)) {
                        return date;
                    }
                    
                    // 处理Date对象
                    const d = new Date(date);
                    const year = d.getFullYear();
                    const month = String(d.getMonth() + 1).padStart(2, '0');
                    const day = String(d.getDate()).padStart(2, '0');
                    return `${year}-${month}-${day}`;
                },
                
                // 添加节假日
                async addHoliday() {
                    try {
                        await this.$refs.holidayFormRef.validate();
                        
                        // 确保公司ID是当前选择的公司
                        this.holidayForm.companyId = this.selectedCompany;
                        
                        // 处理日期格式，避免时区问题
                        const holidayData = { ...this.holidayForm };
                        holidayData.holidayDate = this.formatDateForAPI(holidayData.holidayDate);
                        
                        console.log('发送的节假日数据:', holidayData); // 调试日志
                        
                        const response = await axios.post('/api/holidays', holidayData);
                        
                        ElMessage.success('添加节假日成功');
                        this.showAddHolidayDialog = false;
                        this.resetHolidayForm();
                        this.refreshCalendar();
                    } catch (error) {
                        console.error('添加节假日失败:', error); // 调试日志
                        ElMessage.error('添加节假日失败: ' + error.message);
                    }
                },
                
                // 重置节假日表单
                resetHolidayForm() {
                    this.holidayForm = {
                        companyId: this.selectedCompany,
                        holidayName: '',
                        holidayDate: null,
                        typeId: null,
                        isWorkday: false,
                        description: ''
                    };
                },
                
                // 触发文件选择
                triggerFileInput() {
                    this.$refs.fileInput.click();
                },
                
                // 处理文件选择
                handleFileSelect(event) {
                    const file = event.target.files[0];
                    if (file) {
                        this.selectedFile = file;
                    }
                },
                
                // 导入节假日
                async importHolidays() {
                    if (!this.selectedFile) {
                        ElMessage.warning('请选择文件');
                        return;
                    }
                    
                    try {
                        const formData = new FormData();
                        formData.append('file', this.selectedFile);
                        formData.append('companyId', this.selectedCompany);
                        
                        const response = await axios.post('/api/excel/import/holidays', formData, {
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        });
                        
                        const result = response.data;
                        ElMessage.success(`导入完成！成功: ${result.successCount}, 失败: ${result.failCount}`);
                        
                        this.showImportDialog = false;
                        this.selectedFile = null;
                        this.refreshCalendar();
                    } catch (error) {
                        ElMessage.error('导入失败: ' + error.message);
                    }
                },
                
                // 导出节假日
                async exportHolidays() {
                    if (!this.selectedCompany) {
                        ElMessage.warning('请选择公司');
                        return;
                    }
                    
                    try {
                        const year = this.currentDate.getFullYear();
                        const response = await axios.get('/api/excel/export/holidays', {
                            params: { companyId: this.selectedCompany, year },
                            responseType: 'blob'
                        });
                        
                        const blob = new Blob([response.data], { 
                            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
                        });
                        const url = window.URL.createObjectURL(blob);
                        const link = document.createElement('a');
                        link.href = url;
                        link.download = `节假日_${this.selectedCompany}_${year}.xlsx`;
                        link.click();
                        window.URL.revokeObjectURL(url);
                        
                        ElMessage.success('导出成功');
                    } catch (error) {
                        ElMessage.error('导出失败: ' + error.message);
                    }
                },
                
                // 下载模板
                async downloadTemplate() {
                    try {
                        const response = await axios.get('/api/excel/template/holidays', {
                            responseType: 'blob'
                        });
                        
                        const blob = new Blob([response.data], { 
                            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
                        });
                        const url = window.URL.createObjectURL(blob);
                        const link = document.createElement('a');
                        link.href = url;
                        link.download = '节假日导入模板.xlsx';
                        link.click();
                        window.URL.revokeObjectURL(url);
                        
                        ElMessage.success('模板下载成功');
                    } catch (error) {
                        ElMessage.error('下载模板失败: ' + error.message);
                    }
                }
            },
            watch: {
                selectedCompany(newVal) {
                    if (newVal) {
                        this.holidayForm.companyId = newVal;
                        this.refreshCalendar();
                    }
                }
            }
        }).use(ElementPlus).mount('#app');
    </script>
</body>
</html>
